const express = require('express');
const router = express.Router();
const User = require('../models/User');
const Document = require('../models/Document');
const Card = require('../models/Card');
const Exercise = require('../models/Exercise');
const LearningPath = require('../models/LearningPath');
const UserLearningProgress = require('../models/UserLearningProgress');
const bcrypt = require('bcrypt');
const fs = require('fs');
const path = require('path');
const db = require('../utils/db');

// 只在非生产环境启用测试路由
if (process.env.NODE_ENV !== 'production') {
  // 设置测试数据
  router.post('/setup', async (req, res) => {
    try {
      const { username, email, password } = req.body;
      
      // 创建测试用户
      const hashedPassword = await bcrypt.hash(password, 10);
      const user = new User({
        username,
        email,
        password: hashedPassword
      });
      
      await user.save();
      
      res.status(200).json({ message: '测试数据已设置' });
    } catch (error) {
      console.error('设置测试数据失败:', error);
      res.status(500).json({ message: '设置测试数据失败', error: error.message });
    }
  });
  
  // 清理测试数据
  router.post('/cleanup', async (req, res) => {
    try {
      // 删除测试用户
      await User.deleteMany({ email: /test@/ });
      
      // 查找测试文档
      const testDocuments = await Document.find({ title: /测试/ });
      
      // 删除物理文件
      for (const doc of testDocuments) {
        if (doc.filePath && fs.existsSync(doc.filePath)) {
          try {
            fs.unlinkSync(doc.filePath);
            console.log(`清理测试 - 物理文件已删除: ${doc.filePath}`);
          } catch (fileError) {
            console.error(`清理测试 - 删除物理文件失败: ${doc.filePath}`, fileError);
          }
        }
      }
      
      // 获取所有测试文档的ID
      const testDocumentIds = testDocuments.map(doc => doc._id);
      
      // 删除关联的学习路径和学习进度
      const testLearningPaths = await LearningPath.find({ documentId: { $in: testDocumentIds } });
      const testLearningPathIds = testLearningPaths.map(path => path._id);
      
      await UserLearningProgress.deleteMany({ learningPathId: { $in: testLearningPathIds } });
      await LearningPath.deleteMany({ documentId: { $in: testDocumentIds } });
      
      // 删除测试文档
      await Document.deleteMany({ title: /测试/ });
      
      // 删除相关的卡片和练习题
      await Card.deleteMany({ title: /测试/ });
      await Exercise.deleteMany({ title: /测试/ });
      
      // 清理孤立的上传文件
      const uploadsDir = path.join(__dirname, '../../uploads');
      if (fs.existsSync(uploadsDir)) {
        try {
          const files = fs.readdirSync(uploadsDir);
          let orphanedFilesCount = 0;
          
          for (const file of files) {
            const filePath = path.join(uploadsDir, file);
            // 检查文件是否存在于数据库中
            const fileInDb = await Document.findOne({ filePath });
            
            if (!fileInDb) {
              try {
                fs.unlinkSync(filePath);
                orphanedFilesCount++;
                console.log(`清理测试 - 孤立文件已删除: ${filePath}`);
              } catch (unlinkError) {
                console.error(`清理测试 - 删除孤立文件失败: ${filePath}`, unlinkError);
              }
            }
          }
          
          console.log(`清理测试 - 共删除 ${orphanedFilesCount} 个孤立文件`);
        } catch (dirError) {
          console.error(`清理测试 - 读取上传目录失败:`, dirError);
        }
      }
      
      res.status(200).json({ 
        message: '测试数据已清理',
        details: {
          documentsDeleted: testDocuments.length,
          learningPathsDeleted: testLearningPaths.length,
          progressRecordsDeleted: await UserLearningProgress.countDocuments({ learningPathId: { $in: testLearningPathIds } })
        }
      });
    } catch (error) {
      console.error('清理测试数据失败:', error);
      res.status(500).json({ message: '清理测试数据失败', error: error.message });
    }
  });
  
  // 重置测试数据
  router.post('/reset', async (req, res) => {
    try {
      // 先清理
      await User.deleteMany({ email: /test@/ });
      await Document.deleteMany({ title: /测试/ });
      await Card.deleteMany({ title: /测试/ });
      await Exercise.deleteMany({ title: /测试/ });
      
      // 再设置
      const { username, email, password } = req.body;
      
      const hashedPassword = await bcrypt.hash(password || 'Password123!', 10);
      const user = new User({
        username: username || 'testuser',
        email: email || 'test@example.com',
        password: hashedPassword
      });
      
      await user.save();
      
      res.status(200).json({ message: '测试数据已重置', userId: user._id });
    } catch (error) {
      console.error('重置测试数据失败:', error);
      res.status(500).json({ message: '重置测试数据失败', error: error.message });
    }
  });
  
  // 创建测试文档
  router.post('/documents', async (req, res) => {
    try {
      const { userId, title, description, content } = req.body;
      
      const document = new Document({
        user: userId,
        title: title || '测试文档',
        description: description || '这是一个测试文档',
        content: content || '测试内容',
        fileType: 'txt',
        status: 'processed'
      });
      
      await document.save();
      
      res.status(201).json({ message: '测试文档已创建', documentId: document._id });
    } catch (error) {
      console.error('创建测试文档失败:', error);
      res.status(500).json({ message: '创建测试文档失败', error: error.message });
    }
  });
  
  // 创建测试卡片
  router.post('/cards', async (req, res) => {
    try {
      const { documentId, userId, count } = req.body;
      const cardsCount = count || 5;
      const cards = [];
      
      for (let i = 0; i < cardsCount; i++) {
        const card = new Card({
          document: documentId,
          user: userId,
          title: `测试卡片 ${i + 1}`,
          content: `这是测试卡片 ${i + 1} 的内容`,
          chapter: `第${Math.floor(i / 2) + 1}章`,
          difficulty: ['简单', '中等', '困难'][i % 3],
          tags: ['测试', `标签${i + 1}`],
          position: i
        });
        
        await card.save();
        cards.push(card);
      }
      
      res.status(201).json({ message: '测试卡片已创建', cards });
    } catch (error) {
      console.error('创建测试卡片失败:', error);
      res.status(500).json({ message: '创建测试卡片失败', error: error.message });
    }
  });
  
  // 创建测试练习题
  router.post('/exercises', async (req, res) => {
    try {
      const { cardId, userId, count } = req.body;
      const exercisesCount = count || 3;
      const exercises = [];
      
      const types = ['multiple-choice', 'fill-in-blank', 'coding'];
      
      for (let i = 0; i < exercisesCount; i++) {
        const type = types[i % 3];
        let exercise;
        
        if (type === 'multiple-choice') {
          exercise = new Exercise({
            card: cardId,
            user: userId,
            type,
            question: `这是一个测试选择题 ${i + 1}`,
            options: ['选项A', '选项B', '选项C', '选项D'],
            answer: '选项A',
            explanation: '这是正确答案的解释'
          });
        } else if (type === 'fill-in-blank') {
          exercise = new Exercise({
            card: cardId,
            user: userId,
            type,
            question: `这是一个测试填空题 ${i + 1}，请填写____。`,
            answer: '答案',
            explanation: '这是正确答案的解释'
          });
        } else {
          exercise = new Exercise({
            card: cardId,
            user: userId,
            type,
            question: `这是一个测试代码题 ${i + 1}，请实现以下功能：`,
            codeTemplate: 'function example() {\n  // 请实现功能\n}',
            testCases: [
              { input: '1, 2', expectedOutput: '3' }
            ],
            answer: 'function example(a, b) {\n  return a + b;\n}',
            explanation: '这是正确答案的解释'
          });
        }
        
        await exercise.save();
        exercises.push(exercise);
      }
      
      res.status(201).json({ message: '测试练习题已创建', exercises });
    } catch (error) {
      console.error('创建测试练习题失败:', error);
      res.status(500).json({ message: '创建测试练习题失败', error: error.message });
    }
  });
  
  // 创建完整测试数据集
  router.post('/complete-setup', async (req, res) => {
    try {
      // 清理现有数据
      await User.deleteMany({ email: /test@/ });
      await Document.deleteMany({ title: /测试/ });
      await Card.deleteMany({ title: /测试/ });
      await Exercise.deleteMany({ title: /测试/ });
      
      // 创建用户
      const hashedPassword = await bcrypt.hash('Password123!', 10);
      const user = new User({
        username: 'testuser',
        email: 'test@example.com',
        password: hashedPassword
      });
      
      await user.save();
      
      // 创建文档
      const document = new Document({
        user: user._id,
        title: '测试文档',
        description: '这是一个测试文档',
        content: '测试内容',
        fileType: 'txt',
        status: 'processed'
      });
      
      await document.save();
      
      // 创建卡片
      const cards = [];
      for (let i = 0; i < 5; i++) {
        const card = new Card({
          document: document._id,
          user: user._id,
          title: `测试卡片 ${i + 1}`,
          content: `这是测试卡片 ${i + 1} 的内容`,
          chapter: `第${Math.floor(i / 2) + 1}章`,
          difficulty: ['简单', '中等', '困难'][i % 3],
          tags: ['测试', `标签${i + 1}`],
          position: i
        });
        
        await card.save();
        cards.push(card);
      }
      
      // 创建练习题
      const exercises = [];
      const types = ['multiple-choice', 'fill-in-blank', 'coding'];
      
      for (let i = 0; i < 3; i++) {
        const card = cards[i % cards.length];
        const type = types[i % 3];
        let exercise;
        
        if (type === 'multiple-choice') {
          exercise = new Exercise({
            card: card._id,
            user: user._id,
            type,
            question: `这是一个测试选择题 ${i + 1}`,
            options: ['选项A', '选项B', '选项C', '选项D'],
            answer: '选项A',
            explanation: '这是正确答案的解释'
          });
        } else if (type === 'fill-in-blank') {
          exercise = new Exercise({
            card: card._id,
            user: user._id,
            type,
            question: `这是一个测试填空题 ${i + 1}，请填写____。`,
            answer: '答案',
            explanation: '这是正确答案的解释'
          });
        } else {
          exercise = new Exercise({
            card: card._id,
            user: user._id,
            type,
            question: `这是一个测试代码题 ${i + 1}，请实现以下功能：`,
            codeTemplate: 'function example() {\n  // 请实现功能\n}',
            testCases: [
              { input: '1, 2', expectedOutput: '3' }
            ],
            answer: 'function example(a, b) {\n  return a + b;\n}',
            explanation: '这是正确答案的解释'
          });
        }
        
        await exercise.save();
        exercises.push(exercise);
      }
      
      res.status(200).json({
        message: '完整测试数据已设置',
        data: {
          user: {
            id: user._id,
            username: user.username,
            email: user.email
          },
          document: {
            id: document._id,
            title: document.title
          },
          cards: cards.map(card => ({
            id: card._id,
            title: card.title
          })),
          exercises: exercises.map(exercise => ({
            id: exercise._id,
            type: exercise.type,
            question: exercise.question
          }))
        }
      });
    } catch (error) {
      console.error('设置完整测试数据失败:', error);
      res.status(500).json({ message: '设置完整测试数据失败', error: error.message });
    }
  });
  
  // 清理孤立数据
  router.post('/cleanup-orphans', async (req, res) => {
    try {
      const result = await db.cleanupOrphanData();
      
      res.status(200).json({
        message: '孤立数据清理完成',
        details: result
      });
    } catch (error) {
      console.error('清理孤立数据失败:', error);
      res.status(500).json({ message: '清理孤立数据失败', error: error.message });
    }
  });
}

module.exports = router;